package com.bjpowernode.security03json.handler;

import com.bjpowernode.security03json.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * 登录成功的handler
 */
@Component
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private ObjectMapper objectMapper;

    /**
     * security在登录成功之后会调用这个方法
     * 返回登录成功的提示信息，json格式
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //创建一个Result对象，封装登录成功信息
        Result result = new Result(200, "登录成功");

        //转成json格式  jackson
        String jsonStr = objectMapper.writeValueAsString(result);

        //将json数据响应给前端
        response.getWriter().write(jsonStr);
    }
}
